import React, { useEffect, useRef } from 'react';
import { CreatorType, DocmeeUI } from "@docmee/sdk-ui";

interface DocmeePPTProps {
  token: string;
  onMessage?: (message: unknown) => void;
}

interface DocmeeMessage {
  type: string;
  data?: {
    code?: number;
    message?: string;
    subtype?: string;
    fields?: unknown;
  };
}

const DocmeePPT: React.FC<DocmeePPTProps> = ({ token, onMessage }) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const docmeeRef = useRef<DocmeeUI | null>(null);

  useEffect(() => {
    if (containerRef.current && !docmeeRef.current) {
      // 初始化UI
      docmeeRef.current = new DocmeeUI({
        container: containerRef.current,
        page: "creator-v2",
        token: token,
        mode: "light",
        lang: "zh",
        // 从外部传入主题
        creatorData: {
          type: CreatorType.AI_GEN,
          subject: "Ai行业未来10年的发展预测",
        },
        onMessage: (message: DocmeeMessage) => {
          console.log("监听事件", message);
          if (message.type === "invalid-token") {
            console.log("token 认证错误");
          } else if (message.type === "beforeGenerate") {
            const { subtype, fields } = message.data || {};
            if (subtype === "outline") {
              console.log("即将生成ppt大纲", fields);
              return true;
            } else if (subtype === "ppt") {
              console.log("即将生成ppt", fields);
              return true;
            }
          } else if (message.type === "error") {
            if (message.data?.code === 88) {
              console.error("您的次数已用完");
            } else {
              console.error("发生错误：" + message.data?.message);
            }
          }
          
          // 调用外部传入的onMessage回调
          onMessage?.(message);
        },
      });
    }

    // 组件卸载时清理
    return () => {
      if (docmeeRef.current) {
        docmeeRef.current.destroy();
        docmeeRef.current = null;
      }
    };
  }, [token, onMessage]);

  return (
    <div 
      ref={containerRef} 
      style={{ 
        width: '100%', 
        height: '100vh',
        margin: 0,
        padding: 0,
        borderRadius: '12px',
        overflow: 'hidden',
        background: 'linear-gradient(-157deg, #f57bb0, #867dea)',
      }}
    />
  );
};

export default DocmeePPT; 